#include<iostream>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include"log.hpp"
#include<cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include<string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

log l;

void Usage()
{
    std::cout<<"输入格式:proce ip port"<<std::endl;
}

uint16_t ClientPort;
std::string ClientIp;

class Client
{
public:
    Client(std::string Ip,uint16_t Port)
    :port_(Port)
    ,ip_(Ip)
    {}

    void Init() //跟server建立链接
    {
        socket_=socket(AF_INET,SOCK_DGRAM,0);
        if(socket_<0)
        {
            l(err,"socket创建失败,errno:%d,strerror:%s",errno,strerror(errno));
            _exit(-1);
        }
        l(info,"socket创建成功");

        memset(&c_,0,sizeof(c_));
        c_.sin_addr.s_addr=inet_addr(ip_.c_str());
        c_.sin_port=htons(port_);
        c_.sin_family=AF_INET;
    }

    void Run()
    {
        char buff[size];
        while(true)
        {
            socklen_t len=sizeof(c_);
            std::cin>>buff;
            if(sendto(socket_,buff,strlen(buff),0,reinterpret_cast<struct sockaddr*> (&c_),len)<0)
            {
                l(comm,"(sendto)数据发送失败,errno:%d,strerror:%s",errno,strerror(errno));
                continue;
            }
            l(info,"数据发送成功");
        }
    }
private:
    int socket_;
    uint16_t port_;
    std::string ip_;
    struct sockaddr_in c_;
};

int main(int argc,char *argv[])
{
    if(argc!=3)
        Usage();
    
    ClientIp=argv[1];
    ClientPort=std::stoi(argv[2]); 

    Client C(ClientIp,ClientPort);
    C.Init();
    C.Run();
   
    return 0;
}